package com.jml.第二期.filter;

import com.jml.第二期.utils.JmlJwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
//拦截请求url判断请求方法权限和角色
public class JWTValidationFilter extends BasicAuthenticationFilter {

    public JWTValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 拦截请求，判断是否有角色权限
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头的token的jwt，把里面的角色role拿出来放入Authentication
        try {
            SecurityContextHolder.getContext().setAuthentication
                    (setAuthentication(request.getHeader("token")));
        } catch (ExpiredJwtException e) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.println("过期");
            out.flush();
            out.close();
        }
        super.doFilterInternal(request, response, chain);
    }

    private UsernamePasswordAuthenticationToken setAuthentication(String token) throws Exception {
        String username = null;
        username = JmlJwtUtils.getUsername(token);
        if (!StringUtils.isEmpty(username)) {
            // 解析权限列表
            List<SimpleGrantedAuthority> userRoleList = JmlJwtUtils.getUserRole(token);
            return new UsernamePasswordAuthenticationToken(username, null, userRoleList);
        }
        return null;
    }
}